package rc.alfresco.users;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import rc.database.connection.DBOperations;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: Slejus
 * Date: 13.11.27
 * Time: 12.30
 * To change this template use File | Settings | File Templates.
 */
public class SqlSessionFactoryInstance {

    private SqlSessionFactory instance = null;

    SqlSessionFactoryInstance() {
    }

    public SqlSessionFactory getSqlSessionFactoryInstance() {
        if (instance == null) {
            try {
                createSqlSessionFactoryInstance();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        return instance;
    }

    private SqlSessionFactory  createSqlSessionFactoryInstance() throws IOException {
        Properties props = new Properties();
        /*
        Properties props2 = new Properties();
        props2.setProperty("jdbc.driver","oracle.jdbc.driver.OracleDriver");
        props2.setProperty("jdbc.url","jdbc:oracle:thin:@kadadev.kada.lan:1521:kadadev");
        props2.setProperty("db.username","alfresco");
        props2.setProperty("db.password","alfresco");
        */
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:alfresco/extension/connection-context.xml");
        DBOperations db = (DBOperations)context.getBean("dbOperations"); // DB operations object
        //db.setProperties(props2);

        props.setProperty("db.driver",db.getJdbcDriver());
        props.setProperty("db.url",db.getJdbcUrl());
        props.setProperty("db.username",db.getUsername());
        props.setProperty("db.password",db.getPassword());

        String resource = "myBatisConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        instance = new SqlSessionFactoryBuilder().build(inputStream, props);
        return instance;
    }

}
